package com.kgc.est.utils.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

@Component
public class OSSUtils {
    private final Logger log = LoggerFactory.getLogger(OSSUtils.class);

    @Autowired
    private OssConfig ossConfig;

    /**
     * 获取阿里云OSS客户端对象
     * */
    public final OSS getOSSClient() {
        OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndPoint()
                , ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
        return ossClient;
    }

    /**
     * 文件上传
     * 根据文件全路径名称使用输入流的方式上传文件到oss
     * @param file
     * @param fileName est/brand/huawei/huawei.png
     * @return
     */
    public String uploadByStream(File file, String fileName) {
        String resultStr = null;
        try {
            InputStream is = new FileInputStream(file);
            resultStr = uploadByStream(is, fileName);
        }catch (Exception e){
            log.error("上传阿里云OSS服务器异常:{}", e.getMessage());
        }
        return resultStr;
    }
    /**
     * 文件上传
     * @param is
     * @param fileName est/brand/huawei/huawei.png
     * @return
     */
    public String uploadByStream(InputStream is, String fileName) {
        String resultStr = null;
        OSS ossClient = null;
        try {
            ossClient = getOSSClient();
            PutObjectResult putObjectResult = ossClient.putObject(
                    ossConfig.getBucketName(), fileName, is);
            resultStr = putObjectResult.getETag();
        }catch (Exception e){
            log.error("输入流方式上传阿里云OSS服务器异常:{}", e.getMessage());
        }finally {
            ossClient.shutdown();
        }
        return resultStr;
    }

    /**
     * 下载
     * @param fileId
     * @param fileName 文件名称
     * @return
     */
    public final void download(String fileId, String fileName,
                               HttpServletResponse response) {
        try {
            OSS client = getOSSClient();
            int i = fileName.lastIndexOf("\\");
            fileName = fileName.substring(i + 1);

            //获取fileId对应的阿里云上的文件对象
            OSSObject ossObject = client.getObject(ossConfig.getBucketName(), fileId);
            BufferedInputStream in =
                    new BufferedInputStream(ossObject.getObjectContent());
            BufferedOutputStream out =
                    new BufferedOutputStream(response.getOutputStream());
            //通知浏览器以附件形式下载
            response.setHeader("Content-Disposition", "attachment;filename=" +
                    URLEncoder.encode(fileName, "utf-8"));
            byte[] car = new byte[1024];
            int L = 0;
            while ((L = in.read(car)) != -1) {
                out.write(car, 0, L);
            }
            if (out != null) {
                out.flush();
                out.close();
            }
            if (in != null) {
                in.close();
            }
            // 关闭客户端连接
            client.shutdown();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     *  根据key删除OSS服务器上的文件
     * @param diskName fieldid 文件名称
     * @param fileName 文件名称
     */
    public void deleteFile(String diskName, String fileName) {
        deleteFile(diskName + fileName);
    }

    /**
     *  根据key删除OSS服务器上的文件
     * @param fileName 文件名称
     */
    public void deleteFile(String fileName) {
        OSS client = getOSSClient();
        client.deleteObject(ossConfig.getBucketName(), fileName);
    }

}
